import React, { useEffect, useMemo, useState } from 'react';
import { Drawer, Form, Space, Button, message } from 'antd';
import FormRender from '@/components/FormRender';
import useGetDeptList from '@/components/_hooks/useGetDeptList';
import { encryptByDES } from "@/utils";
import { getRoleList, addMember, editMember } from '@/api';

interface Props {
  id?: number | null;
  isShow: boolean;
  editItem: any;
  onFinish: () => void;
  onSubmit: (...agrs: any[]) => void;
  onCancel: (...agrs: any[]) => void;
  setEditItem: (...agrs: any[]) => void;
}

export default function OperateMemberDrawer({
  id,
  isShow,
  onSubmit,
  onCancel,
  onFinish,
  editItem,
  setEditItem,
}: Props) {
  const [form] = Form.useForm();
  const deptList = useGetDeptList();
  const [roleList, roleName] = useState([]);
  const [loading, setLoading] = useState(false);
  const [changePasswordStatus, setChangePasswordStatus] = useState(false);

  const prefixText = useMemo(() => {
    return !!editItem?.realName ? '编辑' : '新增';
  }, [editItem]);
  const onClose = () => {
    form?.resetFields();
    onCancel?.(null, false);
    setEditItem?.({});
    setChangePasswordStatus(false);
  };
  useEffect(() => {
    if (editItem?.realName) {
      if (editItem?.password) delete editItem.password;
      form?.setFieldsValue(editItem);
    }
  }, [editItem]);

  useEffect(() => {
    if (isShow) {
      getRoleList()
        .then((data) => {
          const list = data.map((i) => {
            return { name: i?.roleName, value: i?.roleId };
          });
          roleName(list);
        })
        .catch((err) => {
          throw err;
        });
    }
  }, [isShow]);

  const isEdit = useMemo(() => !!editItem?.employeeId, [editItem?.employeeId]);

  const submit = async () => {
    const values = await form.validateFields();
    if (!values) return;
    if (values?.changePassword || !isEdit) {
      if (values?.password !== values?.confirmPassword)
        return message.error('确认密码与密码不一致');
    }
    const params = { ...values };
    const requestFn = isEdit ? editMember : addMember;
   
    const { password } = params;
    if (password) {
      params.password = encryptByDES(password);
      delete params?.confirmPassword;
    }

    if (isEdit) {
      params.employeeId = editItem?.employeeId;
    }

    setLoading(true);
    requestFn(params)
      .then((data) => {
        setLoading(false);
        if (!data) return;
        message.success(`${prefixText}成功`);
        onClose();
        onFinish?.();
      })
      .catch((err) => {
        throw err;
      });
  };

  const formItemList = useMemo(() => {
    const changePassword = changePasswordStatus;
    return [
      {
        title: '',
        Items: [
          {
            label: '部门',
            name: 'deptId',
            type: 'select',
            items: deptList,
            rules: [{ required: true }],
          },
          {
            label: '角色',
            name: 'roleId',
            type: 'select',
            items: roleList,
            rules: [{ required: true }],
          },
          {
            label: '姓名',
            name: 'realName',
            type: 'input',
            rules: [
              { required: true },
              { max: 128, message: '最大长度不超过128' },
            ],
          },
          {
            label: '手机号',
            name: 'phone',
            type: 'input',
            rules: [
              { required: true },
              { pattern: /^[0-9]{11}$/, message: '请输入正确的手机号' },
            ],
          },
          {
            label: '性別',
            name: 'gender',
            type: 'select',
            items: [
              { name: '男', value: 'man' },
              { name: '女', value: 'woman' },
            ],
          },
          {
            label: '年龄',
            name: 'age',
            initValue: editItem?.age,
            rules: [{ pattern: /^[0-9]{0,3}$/, message: '请输入正确的年龄' }],
          },
          {
            label: '修改密码',
            name: 'changePassword',
            unenabled: !isEdit,
            operatorNotChange: true,
            defaultValue: changePasswordStatus,
            type: 'radio',
          },
          {
            label: '设置密码',
            name: 'password',
            type: 'input',
            unenabled: !(changePassword || !isEdit),
            rules: [
              { required: true },
              { pattern:  /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/, message: '由大小写字母数字组成，至少6位' },
            ],
          },
          {
            label: '密码确认',
            name: 'confirmPassword',
            type: 'input',
            unenabled: !(changePassword || !isEdit),
            rules: [
              { required: true },
              { pattern:  /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/, message: '由大小写字母数字组成，至少6位' },
            ],
          },
          // {
          //   label: '是否可接单',
          //   name: 'status',
          //   type: 'radio',
          // },
        ],
      },
    ];
  }, [deptList, roleList, editItem, isEdit, changePasswordStatus]);

  const onValuesChange = (values) => {
    if (values?.changePassword !== undefined) {
      setChangePasswordStatus(values?.changePassword);
    }
  };

  return (
    <Drawer
      maskClosable={false}
      title={`${prefixText}员工`}
      open={isShow}
      width={720}
      onClose={onClose}
      destroyOnClose
      extra={
        <Space>
          <Button onClick={onClose}>关闭</Button>
          <Button onClick={submit} type='primary' loading={loading}>
            提交
          </Button>
        </Space>
      }
    >
      <FormRender
        onValuesChange={onValuesChange}
        form={form}
        formItem={formItemList}
      />
    </Drawer>
  );
}
